package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date = begin; !date.isAfter(end); date = date.plusDays(1)) {
            dateList.add(date);
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Double turnover = reportMapper.getTurnover(beginTime, endTime, Orders.COMPLETED);
            turnoverList.add(turnover == null ? 0.0 : turnover);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate date = begin; !date.isAfter(end); date = date.plusDays(1)) {
            dateList.add(date);
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer newUser = reportMapper.getUserCount(beginTime, endTime);
            Integer totalUser = reportMapper.getUserCount(null, endTime);
            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date = begin; !date.isAfter(end); date = date.plusDays(1)) {
            dateList.add(date);
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer orderCount = reportMapper.getOrderCount(beginTime, endTime, null);
            Integer validOrderCount = reportMapper.getOrderCount(beginTime, endTime, Orders.COMPLETED);
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {// 菜品和套餐的销量, key:菜品或套餐名称，value:销量
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesList = reportMapper.getSales(beginTime, endTime, Orders.COMPLETED, 10);
        String nameList = salesList.stream().map(GoodsSalesDTO::getName).collect(Collectors.joining(","));
        String numberList = salesList.stream().map(sales -> String.valueOf(sales.getNumber())).collect(Collectors.joining(","));
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) throws IOException {
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime dateTimeBegin = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime dateTimeEnd = LocalDateTime.of(dateEnd, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(dateTimeBegin, dateTimeEnd);

        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表.xlsx");
        //基于模板文件创建一个新的excel文件
        XSSFWorkbook excel = new XSSFWorkbook(in);
        //填充数据
        XSSFSheet sheet1 = excel.getSheet("Sheet1"); //获取第一个sheet页
        sheet1.getRow(1).getCell(1).setCellValue("时间："+dateBegin+"至"+dateEnd); //设置时间
        sheet1.getRow(3).getCell(2).setCellValue(businessData.getTurnover()); //设置营业额
        sheet1.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate()); //设置订单完成率
        sheet1.getRow(3).getCell(6).setCellValue(businessData.getNewUsers()); //设置新增用户数
        sheet1.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount()); //设置有效订单数
        sheet1.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice()); //设置平均客单价

        int i = 7;
        //填充明细数据
        for (LocalDate date = dateBegin; !date.isAfter(dateEnd); date = date.plusDays(1), i++){
            BusinessDataVO businessDataOneDay = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
            XSSFRow row = sheet1.getRow(i);
            row.getCell(1).setCellValue(date.toString());
            row.getCell(2).setCellValue(businessDataOneDay.getTurnover());
            row.getCell(3).setCellValue(businessDataOneDay.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataOneDay.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessDataOneDay.getUnitPrice());
            row.getCell(6).setCellValue(businessDataOneDay.getNewUsers());
        }

        ServletOutputStream out = response.getOutputStream();
        excel.write(out);

        out.close();
        excel.close();
    }
}
